package controllers.admin.secure;

import controllers.Application;
import controllers.Secure;
import controllers.admin.Admin;
import models.permission.User;
import utils.AuditLogger;

public class Security extends Secure.Security {

	public static final String CURRENT_ROLE_KEY = "currentRole";


	/**
	 * 使用用户名和密码登录
	 * 
	 * @param username
	 *            用户名
	 * @param password
	 *            密码
	 * @return 如果登录成功，返回true，否则false
	 */
	static boolean authenticate(String username, String password) {
		return User.authenticate(username,password);
	}

	/**
	 * 取得当前登录的用户名
	 * 
	 * @return 当前用户名
	 */
	public static String connected() {
		return session.get("username");
	}

	/**
	 * 判断用户是否已登录
	 * 
	 * @return boolean
	 */
	public static boolean isConnected() {
		return  session.contains("username");
	}

	/**
	 * 获取当前用户
	 * 
	 * @return 当前用户
	 */
	public static User currentUser() {
		if (isConnected()) {
			String userName = connected();

			User user = User.findUserByUserName(userName);
			return user;
		} else {
			return null;
			//throw new RuntimeException("not authenticated");
			//return null;
		}
	}


	static void onAuthenticated() {
		User currentUser = Security.currentUser();
		session.put(CURRENT_ROLE_KEY,currentUser.role==null?null:currentUser.role.id);

		AuditLogger.login("%s(%s)-%s",currentUser.userName,currentUser.name,"登录成功");

		Application.index();
	}

	static void onDisconnect() {
		User currentUser = Security.currentUser();
		if(isConnected()) {
			AuditLogger.login("%s(%s)-%s",session.get("username"),session.get("username"),"退出成功");
		}
	}
	
	static void onDisconnected() {
		try {
			Secure.login();
		} catch (Throwable throwable) {
			throwable.printStackTrace();
		}
	}

}
